package cn.com.fuhuitong.main.home.ui.activity

import androidx.lifecycle.Observer
import cn.com.fuhuitong.aroute.ARouteConstance
import cn.com.fuhuitong.main.base.ViewModeActivity
import com.alibaba.android.arouter.facade.annotation.Route
import cn.com.fuhuitong.R
import cn.com.fuhuitong.app.AppConstance
import cn.com.fuhuitong.http.HttpResponseStatus
import cn.com.fuhuitong.main.home.entity.CharityListEntity
import cn.com.fuhuitong.main.home.entity.CharitySignUpEntity
import cn.com.fuhuitong.main.home.vm.CharityViewModel
import com.jakewharton.rxbinding2.widget.RxTextView
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import io.reactivex.functions.BiFunction
import kotlinx.android.synthetic.main.activity_home_charity_enroll.*

@Route(path = ARouteConstance.ACTIVITY_URL_CHARITY_ENROLL)
class HomeCharityEnrollActivity : ViewModeActivity<CharityViewModel>() {

    private var charityListEntity: CharityListEntity? = null

    override fun viewModel(): CharityViewModel = createViewModel()

    override val layoutResId: Int
        get() = R.layout.activity_home_charity_enroll

    override fun initView() {

        image_charity_enroll_back.setOnClickListener {
            this.finish()
        }


        charityListEntity = intent?.getSerializableExtra(AppConstance.BUNDLE_CHARITY_ITEM)
                as? CharityListEntity


        val observableName: Observable<CharSequence> =
            RxTextView.textChanges(text_charity_enroll_name)
        val observableMobile: Observable<CharSequence> =
            RxTextView.textChanges(text_charity_enroll_mobile)
//        val observablePasswordSure: Observable<CharSequence> =
//            RxTextView.textChanges(edit_change_password_sure)

        val observable: Disposable = Observable.combineLatest(observableName, observableMobile,
            BiFunction<CharSequence, CharSequence, Boolean> { t1, t2 ->
                t1.isNotEmpty() && t2.isNotEmpty()
            })
            .subscribe {
                text_charity_enroll_submit.isEnabled = it
            }
        viewModel.dispose().add(observable)

        text_charity_enroll_submit.setOnClickListener {
            viewModel.charitySignUp(
                CharitySignUpEntity(
                    charity_id = (charityListEntity?.id ?: 0).toString(),
                    name = text_charity_enroll_name.text.toString(),
                    mobile = text_charity_enroll_mobile.text.toString(),
                    arrive_time = System.currentTimeMillis()/1000
                )
            )
        }
    }

    override fun initViewMode() {
        viewModel.baseDataLiveData.observe(this, Observer { response ->
            handlerResponseLoading(response.status, response.statusTip)
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            toast(response.response?.msg ?: "报名成功")
        })
    }


}